<template>
    <div class="img-list-box" :style="`height: calc(100% - ${mTop}px);`">
        <div v-if="showImgList" class="img-outer-box">
            <el-upload
                class="upload-demo"
                action="/h5/app/upload"
                :accept="accept"
                :on-success="getImageList"
                :data="{source_type: 1}"
                :with-credentials="true"
                :show-file-list="false">
                <div class="add-img">添加图片</div>
            </el-upload>
            <ul class="img-inner-box" v-if="imageList.length > 0">
                <li class="img-li"
                    v-for="(item, i) in imageList"
                    :key="i"
                    :style="`background-image: url(${item.path});`"
                    :class="{'select-img': item.selected}"
                    @click="selectImg(i);">
                    <i :class="{'checked-icon el-icon-check': item.selected}"/>
                    <i class="del-btn el-icon-circle-close" @click.stop="delImg(item.id, i);"/>
                </li>
            </ul>
            <footer class="footer" v-if="imageList.length > 0">
                <div class="footer-btns">
                    <!--<el-button size="mini">放弃修改</el-button>-->
                    <el-button
                        size="mini"
                        type="primary"
                        @click="showImgList = false;">
                        确 认
                    </el-button>
                </div>
            </footer>
        </div>
        <div v-else class="selected-img" :style="`background-image: url(${content.url})`">
            <div class="img-edit">
                <div class="edit-pic change-pic" @click="showImgList=true;">替换</div>
                <div class="edit-pic del-pic" @click="content.url='';selectImg();">删除</div>
                <div class="edit-pic cut-pic" @click="beforeCut">裁剪</div>
            </div>
        </div>
        <div class="img-tip" v-if="!showImgList">
            <p class="tip-header" v-text="tips.title"/>
            <p class="tip-content"
               v-for="(v, i) of tips.values"
               :key="i"
               v-text="v"/>
        </div>
        <el-dialog
            title="裁剪图片"
            width="30%"
            :visible.sync="dialogVisible"
            :before-close="handleClose">
            <Cropper ref="cropper"
                     :zoomable="option.zoomable"
                     :cropmove="cropmove"
                     :src="content.url"/>
            <span slot="footer" class="dialog-footer">
                <el-button
                    size="mini"
                    @click="dialogVisible = false;">
                    取 消
                </el-button>
                <el-button
                    size="mini"
                    type="primary"
                    @click="onCutImg();">
                    确 定
                </el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import Cropper from 'vue-cropperjs';
    import {prompt} from '@/utils/edit';
    import {getImgList, delImg, uploadBase64} from '@/api/edit';

    export default {
        name: 'ImgList',
        props: {
            mTop: {
                type: Number,
                default: 0
            },
            accept: {
                type: String,
                default: 'image/jpg, image/jpeg, image/webp, image/png, image/gif'
            },
            content: {
                type: Object,
                default: _ => {
                    return {
                        url: ''
                    };
                }
            },
            tips: {
                type: Object,
                default: _ => {
                    return {
                        title: '提示',
                        values: [
                            '1、可支持的图片格式为.jpg，.jpeg，.webp，.png，.gif',
                            '2、建议图片大小控制在1M内',
                            '3、建议图片宽度在320至640像素之间'
                        ]
                    };
                }
            }
        },
        components: {
            Cropper
        },
        created() {
            this.getImageList();
        },
        data() {
            return {
                params: {
                    source_id: '',
                    img_width: 0,
                    img_height: 0,
                    img_base64: ''
                },
                // 当前选中的图片
                currentImg: {},
                showImgList: true,
                dialogVisible: false,
                option: {
                    // 图片是否允许滚轮缩放
                    zoomable: true,
                    // 是否默认生成截图框
                    autoCrop: true,
                    // 裁剪比例 0(表示自由设置裁剪尺寸)
                    aspectRatio: 16 / 9
                },
                imageList: []
            };
        },
        methods: {
            getImageList(response, file, fileList) {
                if (response && response.code !== 0) {
                    prompt(this, 'error', response.message);
                }
                getImgList().then(res => {
                    if (res.code === 0) {
                        let nData = res.data;
                        for (let item of nData) {
                            item.selected = false;
                        }
                        this.imageList = nData.reverse();
                        this.scanImg();
                    }
                });
            },
            delImg(source_id, index) {
                delImg(source_id).then(res => {
                    if (res.code === 0) {
                        this.imageList.splice(index, 1);
                    }
                });
            },
            selectImg(index) {
                for (let i = 0; i < this.imageList.length; i++) {
                    if (i === index) {
                        this.imageList[i].selected = true;
                        this.content.url = this.imageList[i].path;
                        this.currentImg = this.imageList[i];
                    } else {
                        this.imageList[i].selected = false;
                    }
                }
            },
            scanImg() {
                let url = this.content.url;
                if (url) {
                    for (let item of this.imageList) {
                        if (item.path === url) {
                            item.selected = true;
                        } else {
                            item.selected = false;
                        }
                    }
                }
            },
            beforeCut() {
                if (this.content.url) {
                    this.$refs.cropper && this.$refs.cropper.replace(this.content.url);
                    this.dialogVisible = true;
                } else {
                    prompt(this, 'warning', '请先选择一张图片');
                }
            },
            cropmove(ev) {
            },
            onCutImg() {
                this.params.img_base64 = this.$refs.cropper.getCroppedCanvas().toDataURL();
                let _img = new Image();
                _img.addEventListener('load', _ => {
                    this.params.img_width = _img.naturalWidth;
                    this.params.img_height = _img.naturalHeight;
                    this.submitBase64();
                }, false);
                _img.src = this.content.url;
            },
            handleClose(done) {
                this.$confirm('确认关闭？')
                    .then(_ => {
                        done();
                    })
                    .catch(_ => {
                    });
            },
            submitBase64() {
                this.params.source_id = this.currentImg.id;
                uploadBase64(this.params).then(res => {
                    if (res.code === 0) {
                        this.content.url = res.data.url;
                        this.getImageList();
                        this.dialogVisible = false;
                    }
                });
            },
            convertBase64UrlToBlob(urlData) {
                // 将base64的图片转换为file文件
                // 去掉url的头，并转换为byte
                let bytes = window.atob(urlData.split(',')[1]);
                // 处理异常,将ascii码小于0的转换为大于0
                let ab = new ArrayBuffer(bytes.length);
                let ia = new Uint8Array(ab);
                for (let i = 0; i < bytes.length; i++) {
                    ia[i] = bytes.charCodeAt(i);
                }
                return new Blob([ab], {type: 'image/jpeg'});
            }
        }
    }
</script>

<style scoped lang="scss">
    @import "../../../../styles/mixin";

    $color-409EFF: #409EFF;
    @mixin ul-li {
        ul, li {
            margin: 0;
            padding: 0;
            list-style: none;
        }
    }

    .img-list-box {
        width: 100%;
        @include ul-li;
        @include scroll-bar-transparent;

        .img-outer-box {
            position: relative;

            .add-img {
                height: 30px;
                line-height: 30px;
                text-align: center;
                border-radius: 15px;
                cursor: pointer;
                font-weight: 600;
                color: #409EFF;
                border: 1px solid #409EFF;

                &:hover {
                    color: #ffffff;
                    background-color: #409EFF;
                }
            }
            .img-inner-box {
                padding-top: 10px;
                display: flex;
                flex-wrap: wrap;
                justify-content: space-between;

                li.img-li {
                    width: 49%;
                    height: 90px;
                    position: relative;
                    cursor: pointer;
                    margin-bottom: 10px;
                    border: 1px solid #cccccc;
                    box-sizing: border-box;
                    background-position: center;
                    background-repeat: no-repeat;
                    background-size: contain;

                    .del-btn {
                        font-size: 16px;
                        display: none;
                        cursor: pointer;
                    }
                    &:hover .del-btn {
                        display: block;
                        float: right;
                    }
                }
                .select-img {
                    border-color: $color-409EFF;

                    .checked-icon {
                        width: 16px;
                        height: 14px;
                        text-align: center;
                        border-radius: 2px;
                        font-weight: bold;
                        display: block;
                        color: #fff;
                        background-color: $color-409EFF;

                        position: absolute;
                        right: -1px;
                        bottom: -1px;
                    }
                }
            }
            .footer {
                width: 100%;
                height: 50px;
                border-top: 3px solid #cccccc;
                position: absolute;

                display: flex;
                justify-content: flex-end;
                align-items: center;
            }
        }
        .selected-img {
            position: relative;
            height: 160px;
            user-select: none;
            background-repeat: no-repeat;
            background-size: contain;
            background-position: center;
            border: 1px dashed rgba(#000000, .5);

            .img-edit {
                width: 100%;
                position: absolute;
                bottom: 0;
                cursor: pointer;
                display: flex;
                color: #ffffff;
                font-weight: bold;
                background: rgba(0, 0, 0, .5);

                .edit-pic {
                    flex: 1;
                    height: 26px;
                    text-align: center;
                    line-height: 26px;

                    &:hover {
                        background-color: $color-409EFF;
                    }
                }
            }
        }
        .img-tip {
            padding-top: 20px;

            p {
                font-size: 13px;
                color: #BABABA;
                margin: 5px 0;
            }
            .tip-header {
                color: #000000;
            }
        }
    }
</style>
<style lang="scss">
    .img-list-box {
        .img-outer-box {
            .upload-demo {
                width: 100%;
                .el-upload.el-upload--text {
                    width: 100%;
                }
            }
        }
    }
</style>
